import 'dart:async';
import 'package:event_bus/event_bus.dart';
import 'package:people_big_people/utils/log_util.dart';

typedef EventCallback<T> = void Function(T event);

var eventBus = EventBusUtils.instance;

class EventBusUtils {
  static EventBusUtils get instance => _getInstance();
  static EventBusUtils? _instance;

  /// 初始化Utils
  EventBusUtils._internal() {
    _eventBus = EventBus();
  }

  ///初始化eventBus
  late EventBus _eventBus;

  static EventBusUtils _getInstance() {
    return _instance ??= EventBusUtils._internal();
  }

  /// 开启eventbus订阅 并
  StreamSubscription on<T>(EventCallback<T> callback) {
    LogUtil.i("event bus hashCode 订阅 ${_eventBus.hashCode}");
    StreamSubscription stream = _eventBus.on<T>().listen((event) {
      callback(event);
    });
    return stream;
  }

  /// 发送消息
  void emit(event) {
    LogUtil.i("event bus hashCode 发送 ${_eventBus.hashCode}");
    _eventBus.fire(event);
  }

  /// 移除steam
  void off(StreamSubscription steam) {
    steam.cancel();
  }

  ///移除
  void destroy() {
    LogUtil.i("event bus hashCode 移除 ${_eventBus.hashCode}");
    _eventBus.destroy();
  }
}

